package com.liang.cloud.Handler;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liang.cloud.Util.ResultVoUtil;
import com.liang.cloud.Vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局处理blockException
 */
@Slf4j
@Component
public class SellBlockHandler implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        ResultVo errorResponse = null;
        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            errorResponse = ResultVoUtil.error(991,"接口限流了");
        } else if (e instanceof DegradeException) {
            errorResponse = ResultVoUtil.error(992,"服务降级了");
        } else if (e instanceof ParamFlowException) {
            errorResponse = ResultVoUtil.error(993,"热点参数限流了");
        } else if (e instanceof SystemBlockException) {
            errorResponse = ResultVoUtil.error(994,"触发系统保护规则");
        } else if (e instanceof AuthorityException) {
            errorResponse = ResultVoUtil.error(995,"触发系统保护规则");
        }

        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), errorResponse);
    }
}
